package cn.redragon.soa.common.web;


import cn.redragon.soa.common.exception.BaseError;
import cn.redragon.soa.common.exception.CodeableException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseDTO<T> {
    
    public static final String OK = "0";

    public static final String CODE_NODE = "code";

    public static final String DATA_NODE = "data";

    private String code;

    @JsonInclude(Include.NON_NULL)
    private T data;

    private String traceId;

    private ResponseDTO(String code) {
        this.code = code;
    }

    public ResponseDTO(String code, T data) {
        this.code = code;
        this.data = data;
    }

    public static <D> ResponseDTO<D> success(D data) {
        return new ResponseDTO<>(OK, data);
    }

    public static ResponseDTO<Void> success() {
        return new ResponseDTO<>(OK);
    }

    public static ResponseDTO<Void> fail(CodeableException e) {
        return new ResponseDTO<>(e.getCode());
    }

    public static ResponseDTO<Void> fail(BaseError e) {
        return new ResponseDTO<>(e.getCode());
    }

    public static ResponseDTO<Void> fail(String code) {
        return new ResponseDTO<>(code);
    }

    public static <D> ResponseDTO<D> build(String code, D data) {
        return new ResponseDTO<>(code, data);
    }

    public ResponseDTO withTraceId(String traceId) {
        this.traceId = traceId;
        return this;
    }

}
